#include <GL/glut.h>
#include <GL/gl.h>
#include <iostream>
#include <unistd.h>

GLfloat xRotated, yRotated, zRotated;
GLdouble radius = 0.2;

void display(void);
void reshape(int x, int y);
float gravity = 0.00098;
float t = 0;
float pos = 1.0;
float restorePoint = pos;
float factorRP = 0.3; //fator de restauracao
bool up = false;

void draw() {

	glMatrixMode(GL_MODELVIEW);
	glClear(GL_COLOR_BUFFER_BIT);
	glLoadIdentity();
	glTranslatef(0.0, pos, -4.0);
	glColor3f(1, 1, 0);
	glRotatef(xRotated, 1.0, 0.0, 0.0);
	glRotatef(yRotated, 0.0, 1.0, 0.0);
	glRotatef(zRotated, 0.0, 0.0, 1.0);
	glScalef(1.0, 1.0, 1.0);
	glutSolidSphere(radius, 10, 10);
	glFlush();

}

// desenhar a janela e atualizar a tela
void display(void) {
	glTranslatef(0.0, pos, 0.0);
	draw();
	glFlush();

}

void reshape(int x, int y) {
	if (y == 0 || x == 0)
		return;
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(39.0, (GLdouble) x / (GLdouble) y, 0.6, 21.0);
	glMatrixMode(GL_MODELVIEW);
	glViewport(0, 0, x, y);
}

void restart() {
	pos = 1.0;
	restorePoint = 1.0;
	t = 0;
	draw();
	display();
}

void keyPressed(unsigned char key, int x, int y) {
	//tecla "G" queda livre de acordo com gravidade, "L" linearmente, "Q" Quit
	// outra tecla pra reiniciar.
	if ((key == 'q') || (key == 'Q'))
		exit(0);

	if ((key == 'g') || (key == 'G')) {
		do {
			if (up) {
				pos += (gravity * t);
				t -= 0.03;
				if (t <= 0) {
					up = false;
					t = 0;
				}
			} else {
				pos -= (gravity * t);
				t += 0.02;
				if (pos < -1.0) {
					up = true;
				}
			}
			display();
		} while (pos > -1.0 || t > 0.2);

//		do {
//			while (pos > -1.0) {
//				//nova posicao pra desenhar
//				pos -= (gravity * t) / 2;
//				t = t + 0.02;
//
//				display();
//			}
//
//			restorePoint -= factorRP; //fator de restauracao, novo ponto de altura max.
//
//			while (pos < restorePoint) {
//				pos += (gravity * t) / 2; //nova posicao
//				t = t - 0.02;
//
//				display();
//			}
//
//		} while (restorePoint > -1.0);
	}

	else if ((key == 'l') || (key == 'L')) {
		do {

			while (pos > -1.0) {
				pos -= 0.01;
				glTranslatef(0.0, pos, 0.0);
				draw();
				display();
			}

			if (pos < -1.0) {
				pos = -1.0;
			} else {
				restorePoint -= factorRP;
			}

			while (pos < restorePoint) {
				pos += 0.01;
				glTranslatef(0.0, pos, 0.0);
				draw();
				display();
			}
		} while (restorePoint > -1.0);
	} else
		restart();
}

int main(int argc, char **argv) {
	glutInit(&argc, argv);
	glutInitWindowSize(800, 600);
	glutCreateWindow("Projeto CG");
	xRotated = yRotated = zRotated = 30.0;
	xRotated = 43;
	yRotated = 50;

	glutDisplayFunc(display);
	glutKeyboardFunc(keyPressed);
	glutReshapeFunc(reshape);
	glutMainLoop();
	return 0;
}

